<?php
    
        include('confdb.php');

        $sud = $_POST['sud'] ?? '';
        $kol_sud = $_POST['kol_sud'] ?? '';
        $nomer_kort = $_POST['nomer_kort'] ?? '';
        $del = $_POST['del'] ?? '';
        $otkl = $_POST['otkl'] ?? '';
        $num = $_POST['num'] ?? '';
        $sys = $_POST['sys'] ?? '';

        $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);

        if ($del != 0) {
            
            $query = "DELETE FROM connect WHERE connect_sud ='$otkl' and nomer_kort = '$num'";
            $result = mysqli_query($con, $query) or die("Ошибка " . mysqli_error($conn));
            
            echo "OK del";
            
        } else {

            $zap = "SELECT * FROM connect";
            $zapis = mysqli_query($con, $zap);

            $row = mysqli_fetch_array($zapis, MYSQLI_ASSOC);

            if ($row['connect_sud'] == 0 or $row['connect_sud'] == null) {

                $query = "INSERT INTO connect (connect_sud, kol_sud, nomer_kort, sys) VALUES ('$sud', '$kol_sud', '$nomer_kort', '$sys')";

                $result = mysqli_query($con, $query);

                echo "OK connect";

            } else {
                
                $query = "SELECT * FROM connect where nomer_kort = '$nomer_kort'";
                $result = mysqli_query($con, $query) or die("Ошибка " . mysqli_error($conn));
                
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
                
                if ($row['nomer_kort'] != $nomer_kort) {

                        $query = "INSERT INTO connect (connect_sud, kol_sud, nomer_kort, sys) VALUES ('$sud', '$kol_sud', '$nomer_kort', '$sys')";

                        $result = mysqli_query($con, $query);

                        echo "OK connect";
                    
                }

            }
            
        }

?>